package com.ykq.sso.controller;

import com.alibaba.fastjson.JSON;
import com.ykq.pojo.entity.User;
import com.ykq.pojo.vo.CommonResult;
import com.ykq.sso.feign.PermissionFeign;
import com.ykq.sso.vo.LoginVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @program: qy151-education-parent
 * @description:
 * @author: 闫克起2
 * @create: 2022-08-29 09:48
 **/
@RestController
@RequestMapping("/sso")
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PermissionFeign permissionFeign;

    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginVo loginVo){
        Subject subject = SecurityUtils.getSubject();
        try{
            UsernamePasswordToken token=new UsernamePasswordToken(loginVo.getUsername(),loginVo.getPassword());
            //交于shiro自定义realm中的认证方法
            subject.login(token);

            //生成token. (1)UUID生成一个唯一id并把该值保存到redis中 [2]通过JWT来生成token.[(1)头信息 (2)载体 (3)密钥]
            String uuid= UUID.randomUUID().toString().replace("-","");
            //登录成功后的用户信息
            User user = (User) subject.getPrincipal();
            user.setPassword(null);
            //根据用户id查询该用户具有的权限。
            List<String> permissions=permissionFeign.findPermissionByUserid(user.getId());
            //getData():LinkedHashMap
            Map<String,Object> map=new HashMap<>();
            map.put("user",user);
            map.put("permissions",permissions);
            // 保存在redis中 value应该为包含用户信息以及该用户具有的权限
            redisTemplate.opsForValue().set(uuid, JSON.toJSONString(map),24, TimeUnit.HOURS);
            return new CommonResult(2000,"登录成功",uuid);
        }catch (Exception e){
            e.printStackTrace();
            return new CommonResult(5000,"账号或密码错误",null);
        }
    }
}





















